package com.cn.main.framework.proxy;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Objects;
//import org.springframework.cglib.proxy.InvocationHandler;
//import org.springframework.cglib.proxy.Proxy;

/**
 * user : chenyuncong
 * create_time : 2022/9/3
 */
public class RunFactoryBean <T> implements FactoryBean<T> {
    private Class<T> interfaceType;
    private String serviceName;
    private RestTemplate restTemplate;

    public Class<T> getInterfaceType() {
        return interfaceType;
    }



    @Override
    public T getObject() throws Exception {
//        InvocationHandler handler = (proxy, method, args) -> {
//            System.out.println("代理T类型做一些事情");
//            return null;
//        };

        if(Objects.isNull(restTemplate)){
            HttpProxy httpProxy = new HttpProxy(interfaceType,serviceName);
            return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(),
                    new Class[]{interfaceType}, httpProxy);
        }

        HttpProxy httpProxy = new HttpProxy(interfaceType,serviceName,restTemplate);
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(),
                new Class[]{interfaceType}, httpProxy);
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceType;
    }


    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void setInterfaceType(Class<T> interfaceType) {
        this.interfaceType = interfaceType;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }
}
